<template>
  <!-- 登录-->
  <div class="login">
    <!-- 账密登录 -->
    <div class="login_password" v-if="typeShow">
      <div>密码登录<img :src="require('@/assets/images/other/login.png')" alt="" /></div>
      <input
        type="number"
        placeholder="请输入手机号码"
        v-model="mobile"
        @blur="mobileBlur"
      />
      <input type="password" placeholder="请输入你的密码" v-model="password" />
      <div @click="loginClick">登录</div>
      <div>
        <div @click="passwordChange">验证码登录</div>
        <!-- <div>忘记密码？</div> -->
      </div>
    </div>
    <!-- 验证码登录 -->
    <div class="login_code" v-else>
      <div>
        验证码登录/注册<img :src="require('@/assets/images/other/login.png')" alt="" />
      </div>
      <input type="number" placeholder="请输入手机号码" v-model="mobile" />
      <p>未注册的手机号验证后自动创建账户</p>
      <div>
        <input type="number" placeholder="请输入验证码" v-model="code" />
        <div @click="sendCode">{{ codetext }}</div>
      </div>
      <div @click="logincodeClick">登录</div>
      <div @click="codeChange">密码登录</div>
    </div>
    <div class="login_xieyi">
      <input type="checkbox" v-model="xieyishow" />
      <div>勾选则表示已阅读并同意<span>《声贝用户协议》</span></div>
    </div>
    <!-- <p><span>——</span>您也可以用以下方式登录<span>——</span></p> -->
    <!-- 微信登录 -->
    <!-- <div @click="wechatLogin">
      <img src="../../public/img/other/wechat.png" alt="" />
      微信登录
    </div> -->
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from 'vue'
import { userSendRegCode, indexGetOpenId, userIsReg, userLogin, userCodelogin } from '@/api/recharge'
import { setCookie } from '@/util/cookie'
import { useRouter, useRoute } from 'vue-router'
import { Toast } from 'vant'
import 'vant/lib/index.css'
export default defineComponent({
    setup() {
        const router: any = useRouter()
        const route: any = useRoute()
        const data = reactive<Record<string, any>>({
            mobile: "", //手机号
            password: "", //密码
            mobileShow: false,
            typeShow: true,
            xieyishow: false,
            codetext: "发送",
            code: "", //验证码
            codeTime: true,
        })
        const sendCode = async (): Promise<void> =>  {
            if (data.codeTime) {
                const arys = { 
                    phone: data.mobile, 
                    type: 5,
                    country_code: "" 
                }
                const dataRes = await userSendRegCode(arys)
                Toast(dataRes.data.text);
                if (dataRes.data.status == 0) {
                    data.codeTime = false;
                    let time = 59;
                    let timer = setInterval(() => {
                        data.codetext = time + "s";
                        time = time - 1;
                        if (time == 0) {
                            data.codetext = "发送";
                            clearInterval(timer);
                        }
                    }, 1000);
                }
            } else {
                Toast("请勿重复点击");
            }
        }
        const passwordChange = (): void => {
            data.typeShow = false;
        }
        const codeChange = (): void => {
            data.typeShow = true;
        }
        const wechatLogin = (): void => {
            let codeUrl = "";
            let url = encodeURIComponent("http://api.guotianyuewan.com/h5/#/login");
            codeUrl =
                "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc051f7e1f2031268&redirect_uri=" +
                url +
                "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
            location.href = codeUrl;
        }
        const getUserInfo = async (): Promise<void> => {
            //根据code获取用户信息
            const arys = {
                code: data.loginCode
            }
            const dataRes = await indexGetOpenId(arys)
            if (dataRes.data.result.is_register == 0) {
                setCookie("token", dataRes.data.result.user_info.token, 180);
                setCookie("userId", dataRes.data.result.user_info.userId, 180);
                setTimeout(() => {
                    router.push({
                        path: route.query.reductName
                    });
                }, 500);
            } else {
                Toast("你还未注册会员，请登录APP注册");
            }
        }
        const mobileBlur = async (): Promise<void> => {
            if (data.mobile) {
                const params = {
                    phone: data.mobile
                }
                const dataRes = await userIsReg(params)
                console.log(dataRes)
                if (dataRes.data.status !== 101) {
                    Toast("你还未注册会员，请登录APP注册");
                }
            }
        }
        const loginClick = async (): Promise<void> => {
            //登录
            if (!data.xieyishow) {
                Toast("请勾选用户协议并继续");
                return 
            }
            if (!data.mobile) {
                Toast("手机号不能为空");
                return 
            }
            if (!data.password) {
                Toast("密码不能为空");
                return 
            }
            const params = {
                mobile: data.mobile,
                password: data.password,
            }
            const dataRes = await userLogin(params)
            if (dataRes.data.status == 0) {
                setCookie(
                    "token",
                    dataRes.data.result.token,
                    dataRes.data.result.tokenExpiryTime
                );
                setCookie(
                    "userId",
                    dataRes.data.result.userId,
                    dataRes.data.result.tokenExpiryTime
                );
                returnPage()
            } else {
                Toast(dataRes.data.text);
                data.password = "";
            }
        }
        const returnPage = ():void => {
            setTimeout(() => {
                router.push({
                    path: route.query.reductName
                });
            }, 500);
        }
        const logincodeClick = async (): Promise<void> => {
            //登录
            if (data.mobile) {
                if (data.code) {
                    if (data.xieyishow) {
                        let params = {
                            mobile: data.mobile,
                            authCode: data.code,
                        }
                        const dataRes = await userCodelogin(params)
                        if (dataRes.data.status == 0) {
                            setCookie(
                                "token",
                                dataRes.data.result.token,
                                dataRes.data.result.tokenExpiryTime
                            );
                            setCookie(
                                "userId",
                                dataRes.data.result.userId,
                                dataRes.data.result.tokenExpiryTime
                            );
                            returnPage();
                        } else {
                            console.log(dataRes)
                            Toast(dataRes.data.text);
                            data.password = "";
                        }
                    } else {
                        Toast("请勾选用户协议并继续");
                    }
                } else {
                    Toast("验证码不能为空");
                }
            } else {
                Toast("手机号不能为空");
            }
        }
        getUserInfo()
        return {
            sendCode,
            mobileBlur,
            wechatLogin,
            loginClick,
            logincodeClick,
            passwordChange,
            codeChange,
            ...toRefs(data)
        }
    }
})
</script>

<style lang="less" scoped>
@import './LoginComponent.less';
</style>